package com.woniu.config;


import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

@Configuration
@ComponentScan("com.woniu.service")
@EnableTransactionManagement
public class RootConfig {

    @Bean
    public DataSource ds(){
        DruidDataSource ds = new DruidDataSource();
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("application.properties");
        Properties properties = new Properties();
        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        ds.setDriverClassName(properties.getProperty("driverClassName"));
        ds.setUsername(properties.getProperty("username"));
        ds.setPassword(properties.getProperty("password"));
        ds.setUrl(properties.getProperty("url"));
        return ds;

    }

    @Bean
    public SqlSessionFactoryBean sb(DataSource ds){
        SqlSessionFactoryBean sb = new SqlSessionFactoryBean();
        sb.setDataSource(ds);
        sb.setTypeAliasesPackage("com.woniu.entity");
        ClassPathResource classPathResource = new ClassPathResource("mybatis-config.xml");
        sb.setConfigLocation(classPathResource);
        return sb;
    }

    @Bean
    public MapperScannerConfigurer msc() {
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        msc.setBasePackage("com.woniu.mapper");
        return msc;
    }

    @Bean
    public DataSourceTransactionManager tm(DataSource ds) {
        DataSourceTransactionManager tm = new DataSourceTransactionManager();
        tm.setDataSource(ds);
        return tm;
    }
}
